<template>
  <div class="householder-query">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>户主信息查询</h2>
      <p>查询和管理户主信息，支持多条件筛选和详细信息查看</p>
    </div>

    <!-- 查询表单 -->
    <el-card class="query-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>查询条件</span>
          <el-button type="text" @click="resetQuery">重置</el-button>
        </div>
      </template>
      
      <el-form :model="queryForm" label-width="100px" :inline="true">
        <el-form-item label="户主姓名">
          <el-input
            v-model="queryForm.name"
            placeholder="请输入户主姓名"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        
        <el-form-item label="身份证号">
          <el-input
            v-model="queryForm.idCard"
            placeholder="请输入身份证号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        
        <el-form-item label="户籍地址">
          <el-input
            v-model="queryForm.address"
            placeholder="请输入户籍地址"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
      
    <!-- 统计信息 -->
    <div class="statistics-panel">
      <div class="stat-card">
        <div class="stat-icon">
          <el-icon><User /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.totalHouseholders }}</div>
          <div class="stat-label">户主总数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon success">
          <el-icon><CircleCheck /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.normalHouseholds }}</div>
          <div class="stat-label">正常户口</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon warning">
          <el-icon><CircleClose /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.movedOutHouseholds }}</div>
          <div class="stat-label">已迁出</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon info">
          <el-icon><DataAnalysis /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.avgFamilySize }}</div>
          <div class="stat-label">平均家庭人数</div>
        </div>
      </div>
      
    </div>

    <!-- 查询结果 -->
    <el-card class="result-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>查询结果</span>
          <el-tag type="info" size="small">共 {{ pagination.total }} 条记录</el-tag>
        </div>
      </template>

      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="户主姓名" width="120" align="center">
          <template #default="{ row }">
            <el-tag type="primary" size="small">{{ row.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="idCard" label="身份证号" width="180" align="center">
          <template #default="{ row }">
            <span class="id-card">{{ formatIdCard(row.idCard) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.gender === 1 ? 'primary' : 'danger'" size="small">
              {{ formatGender(row.gender) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="birthDate" label="出生日期" width="120" align="center">
          <template #default="{ row }">
            {{ formatDate(row.birthDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="户籍地址" min-width="200">
          <template #default="{ row }">
            <el-tooltip :content="row.address" placement="top">
              <span class="address-text">{{ row.address }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="householdNumber" label="户号" width="140" align="center">
          <template #default="{ row }">
            <el-tag type="info" size="small">{{ row.householdNumber }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="viewHouseholdDetail(row)">
                <el-icon><View /></el-icon>
                详情
              </el-button>
              <el-button type="success" size="small" @click="viewMembers(row)">
                <el-icon><UserFilled /></el-icon>
                成员
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>

    <!-- 户口详情对话框 -->
    <el-dialog
      v-model="householdDetailVisible"
      title="户口详细信息"
      width="80%"
      :before-close="handleCloseDetail"
    >
      <div v-if="selectedHousehold">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="户主姓名">{{ selectedHousehold.householderName }}</el-descriptions-item>
          <el-descriptions-item label="户号">{{ selectedHousehold.householdCode }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ selectedHousehold.idCard }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ formatGender(selectedHousehold.gender) }}</el-descriptions-item>
          <el-descriptions-item label="出生日期">{{ formatDate(selectedHousehold.birthDate) }}</el-descriptions-item>
          <el-descriptions-item label="户籍地址" :span="2">{{ selectedHousehold.address }}</el-descriptions-item>
          <el-descriptions-item label="家庭人数">{{ selectedHousehold.memberCount }}人</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="selectedHousehold.status === 1 ? 'success' : 'warning'">
              {{ selectedHousehold.status === 1 ? '正常' : '迁出' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="householdDetailVisible = false">关闭</el-button>
          <el-button type="primary" @click="editHouseholder">编辑户主信息</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 家庭成员对话框 -->
    <el-dialog
      v-model="membersVisible"
      title="家庭成员信息"
      width="90%"
      :before-close="handleCloseMembers"
    >
      <el-table :data="membersList" border stripe>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="姓名" width="100" align="center" />
        <el-table-column prop="relationship" label="与户主关系" width="120" align="center" />
        <el-table-column prop="idCard" label="身份证号" width="180" align="center" />
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="{ row }">
            {{ formatGender(row.gender) }}
          </template>
        </el-table-column>
        <el-table-column prop="birthDate" label="出生日期" width="120" align="center">
          <template #default="{ row }">
            {{ formatDate(row.birthDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'warning'" size="small">
              {{ row.status === 1 ? '正常' : '迁出' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="membersVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  View, 
  Edit, 
  User, 
  UserFilled, 
  Switch, 
  Clock,
  ArrowDown,
  CircleCheck,
  CircleClose,
  DataAnalysis
} from '@element-plus/icons-vue'
import axios from 'axios'
import { API_BASE_URL } from '@/config/api'

const loading = ref(false)
const tableData = ref([])
const householdDetailVisible = ref(false)
const membersVisible = ref(false)
const selectedHousehold = ref(null)
const membersList = ref([])

const queryForm = reactive({
  name: '',
  idCard: '',
  address: ''
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const statistics = reactive({
  totalHouseholders: 0,
  normalHouseholds: 0,
  movedOutHouseholds: 0,
  avgFamilySize: 0
})

// 获取户主列表数据
const fetchHouseholderList = async () => {
  loading.value = true
  
  try {
    const params = {
      name: queryForm.name || undefined,
      idCard: queryForm.idCard || undefined,
      address: queryForm.address || undefined,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === undefined || params[key] === '') {
        delete params[key]
      }
    })

    const response = await axios.get(`${API_BASE_URL}/household/queryHouseholder`, {
      params
    })

    if (response.data.status === 200) {
      const data = response.data.data || []
      tableData.value = data
      
      // 更新分页信息 - 注意：后端可能需要返回总数，这里先用数据长度
      pagination.total = data.length
      
      // 更新统计信息
      updateStatistics(data)
      
      ElMessage.success('查询成功')
    } else {
      ElMessage.error(response.data.msg || '查询失败')
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('查询户主信息失败:', error)
    ElMessage.error('查询失败，请检查网络连接')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 更新统计信息
const updateStatistics = (data) => {
  statistics.totalHouseholders = data.length
  statistics.normalHouseholds = data.length // 由于后端只返回户主信息，暂时都算正常
  statistics.movedOutHouseholds = 0
  statistics.avgFamilySize = 0 // 后端暂未返回家庭人数信息
}

const handleQuery = () => {
  pagination.currentPage = 1
  fetchHouseholderList()
}

const resetQuery = () => {
  queryForm.name = ''
  queryForm.idCard = ''
  queryForm.address = ''
  pagination.currentPage = 1
  fetchHouseholderList()
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchHouseholderList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchHouseholderList()
}

// 查看户口详情
const viewHouseholdDetail = (row) => {
  selectedHousehold.value = row
  householdDetailVisible.value = true
}

// 查看家庭成员
const viewMembers = (row) => {
  // 这里可以调用获取家庭成员的接口
  membersList.value = [] // 暂时为空，等待后端接口
  membersVisible.value = true
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  const { action, row } = command
  
  switch (action) {
    case 'edit':
      ElMessage.info(`编辑 ${row.name} 的信息`)
      break
    case 'transfer':
      ElMessage.info(`办理 ${row.name} 的户口迁移`)
      break
    case 'history':
      ElMessage.info(`查看 ${row.name} 的变更历史`)
      break
  }
}

const handleCloseDetail = () => {
  householdDetailVisible.value = false
  selectedHousehold.value = null
}

const handleCloseMembers = () => {
  membersVisible.value = false
  membersList.value = []
}

const editHouseholder = () => {
  ElMessage.info('跳转到编辑页面')
  householdDetailVisible.value = false
}

// 格式化身份证号显示
const formatIdCard = (idCard) => {
  if (!idCard) return '-'
  return idCard.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2')
}

// 格式化性别显示
const formatGender = (gender) => {
  if (gender === 1) return '男'
  if (gender === 2) return '女'
  return '未知'
}

// 格式化日期显示
const formatDate = (date) => {
  if (!date) return '-'
  const d = new Date(date)
  return d.toLocaleDateString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  fetchHouseholderList()
})
</script>

<style lang="scss" scoped>
.householder-query {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .page-header {
    margin-bottom: 20px;
    
    h2 {
      color: #303133;
      margin-bottom: 8px;
      font-size: 24px;
      font-weight: 600;
    }
    
    p {
      color: #909399;
      font-size: 14px;
      margin: 0;
    }
  }

  .query-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      span {
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .statistics-panel {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 20px;

    .stat-card {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-radius: 12px;
      padding: 20px;
      color: white;
      display: flex;
      align-items: center;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      transition: transform 0.3s ease;

      &:hover {
        transform: translateY(-2px);
      }

      &:nth-child(2) {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }

      &:nth-child(3) {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }

      &:nth-child(4) {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      }

      .stat-icon {
        font-size: 32px;
        margin-right: 15px;
        opacity: 0.8;

        &.success {
          color: #67c23a;
        }

        &.warning {
          color: #e6a23c;
        }

        &.info {
          color: #409eff;
        }
      }

      .stat-content {
        .stat-number {
          font-size: 28px;
          font-weight: bold;
          line-height: 1;
          margin-bottom: 4px;
        }

        .stat-label {
          font-size: 14px;
          opacity: 0.9;
        }
      }
    }
  }

  .result-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      span {
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .id-card {
    font-family: 'Courier New', monospace;
    font-size: 13px;
    color: #606266;
  }

  .address-text {
    display: inline-block;
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .action-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
    align-items: center;
    
    .el-button {
      margin: 0;
    }
  }

  .member-badge {
    :deep(.el-badge__content) {
      background-color: #409eff;
    }
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}

// 对话框样式
:deep(.el-dialog) {
  .el-dialog__header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 20px;
    
    .el-dialog__title {
      color: white;
      font-weight: 600;
    }
    
    .el-dialog__headerbtn .el-dialog__close {
      color: white;
      
      &:hover {
        color: #f0f0f0;
      }
    }
  }
  
  .el-dialog__body {
    padding: 20px;
  }
}

// 表格样式优化
:deep(.el-table) {
  .el-table__header-wrapper {
    .el-table__header {
      th {
        background: #f8f9fa !important;
        color: #495057;
        font-weight: 600;
        border-bottom: 2px solid #dee2e6;
      }
    }
  }
  
  .el-table__body-wrapper {
    .el-table__row {
      &:hover {
        background-color: #f8f9fa;
      }
      
      &.el-table__row--striped {
        background-color: #fafbfc;
        
        &:hover {
          background-color: #f1f3f4;
        }
      }
    }
  }
}

// 分页样式
:deep(.el-pagination) {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  
  .el-pagination__total {
    color: #606266;
    font-weight: 500;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .statistics-panel {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .householder-query {
    padding: 10px;
  }
  
  .statistics-panel {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
    
    .el-button {
      width: 100%;
      margin: 0;
    }
  }
}
</style>